package com.meepo.feed.feed

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.meepo.basic.router.RouterManager
import com.meepo.basic.components.listfragment.MeepoListFragment
import com.meepo.basic.components.listfragment.ListFragmentParams
import com.meepo.basic.schema.Enums
import com.meepo.basic.schema.UMengEvent
import com.meepo.basic.schema.common.PageResult
import com.meepo.basic.schema.common.ResponseWrapper
import com.meepo.basic.umeng.IShareListener
import com.meepo.basic.umeng.ShareContent
import com.meepo.basic.umeng.UMengManager
import com.meepo.framework.design.desc.DescLayout
import com.meepo.framework.design.helper.ImageLoader
import com.meepo.feed.R
import com.meepo.feed.API

import com.meepo.basic.schema.feed.Attitude
import com.meepo.basic.schema.feed.Item
import com.meepo.feed.Func
import com.meepo.framework.design.recycler.ViewHolder
import com.meepo.sdk.utils.ActivityHelper
import com.umeng.analytics.MobclickAgent
import com.xiaojinzi.component.support.ParameterSupport
import io.reactivex.Observable

open class FeedListFragment : MeepoListFragment<Item>() {

    companion object {
        fun instance(
            category: String = "",
            keyword: String = "",
            topicId: String = "",
            hideTopicView: Boolean = false,
            listFragmentParams: ListFragmentParams = ListFragmentParams()
        ): FeedListFragment {

            val rsp = FeedListFragment()

            val bundle = Bundle()
            bundle.putString("category", category)
            bundle.putString("keyword", keyword)
            bundle.putString("topicId", topicId)
            bundle.putBoolean("hideTopicView", hideTopicView)
            bundle.putSerializable("listFragmentParams", listFragmentParams)

            rsp.arguments = bundle

            return rsp
        }
    }

    override fun loadDataObservable(page: Int): Observable<ResponseWrapper<PageResult<Item>>> {
        val category = ParameterSupport.getString(arguments, "category") ?: ""
        val keyword = ParameterSupport.getString(arguments, "keyword") ?: ""
        val topicId = ParameterSupport.getString(arguments, "topicId") ?: ""

        return API.instance().fetchFeedItemsV2(category = category, keyword = keyword, topicId = topicId, page = page)
    }

    @SuppressLint("SetTextI18n")
    override fun bind(item: Item, holder: ViewHolder, position: Int) {

        // title
        holder.setText(R.id.item_title_tv, item.title)

        // 标签
        holder.getView<RecyclerView>(R.id.tag_recycler_view)?.let {
            ItemRender.renderTags(requireContext(), it, item.tags)
        }

        // 封面图
        ItemRender.renderCovers(
            requireContext(), item,
            holder.getView(R.id.multi_images_recycler_view)!!,
            holder.getView(R.id.big_vertical_image_view)!!,
            holder.getView(R.id.iv_1)!!,
            holder.getView(R.id.video_ctrl_iv)!!
        )

        // 分类，话题
        val hideTopicView = ParameterSupport.getBoolean(arguments, "hideTopicView") ?: false

        holder.getView<RelativeLayout>(R.id.topic_rl)?.visibility = if (hideTopicView) View.GONE else View.VISIBLE
        holder.getView<TextView>(R.id.topic_tv)?.let {
            ItemRender.renderTopic(requireContext(), it, item.topic)
        }

        // 作者信息
        holder.getView<DescLayout>(R.id.userinfo_view)?.let {
            ItemRender.renderAuthor(requireContext(), it, item.author)
        }

        // 统计
        holder.setText(R.id.share_count_tv, "" + (item.stat?.sharedCount ?: 0))
        holder.setText(R.id.comment_count_tv, "" + (item.stat?.commentCount ?: 0))
        holder.setText(R.id.like_count_tv, "" + (item.stat?.likedCount ?: 0))

        // 分享
        holder.getView<LinearLayout>(R.id.share_ll)?.setOnClickListener {
            UMengManager.shareWebByBoard(
                requireActivity(),
                ShareContent(
                    title = item.title ?: "", desc = item.title ?: "",
                    url = item.h5?.content ?: "", iconPath = item.findOneCover()
                ),
                object : IShareListener {
                    override fun onStart(media: String) {
                    }

                    override fun onResult(media: String) {
                        onShare(item, position, media)
                    }

                    override fun onError(media: String, e: Throwable) {
                    }

                    override fun onCancel(media: String) {
                    }
                })
        }

        // 评论
        holder.getView<LinearLayout>(R.id.comment_ll)?.setOnClickListener {
            toDetail(item, hideTopicView)
        }

        // 喜欢
        holder.getView<LinearLayout>(R.id.like_ll)?.setOnClickListener {

            item.notifyLikeChanged()

            this.replace(position, item.notifyLikeChanged())

        }

        renderAttitude(holder, R.id.attitude_1_iv, R.id.attitude_1_tv, R.id.attitude_1_ll, 0, item, position)
        renderAttitude(holder, R.id.attitude_2_iv, R.id.attitude_2_tv, R.id.attitude_2_ll, 1, item, position)
        renderAttitude(holder, R.id.attitude_3_iv, R.id.attitude_3_tv, R.id.attitude_3_ll, 2, item, position)
        renderAttitude(holder, R.id.attitude_4_iv, R.id.attitude_4_tv, R.id.attitude_4_ll, 3, item, position)

        // 删除
        holder.getView<ImageView>(R.id.close_iv)?.setOnClickListener {
            this.remove(position, holder.adapterPosition)
        }

        // 点击事件
        holder.setOnItemClickListener(View.OnClickListener {
//            RouterManager.FeedModule.routeToFeedComment(requireContext(), item.id, true)
            toDetail(item, hideTopicView)
            // 记录浏览历史
            MobclickAgent.onEvent(requireContext(), UMengEvent.EnterDetail)

            Func.saveReadHistory(item)
        })
    }

    private fun toDetail(item: Item, hideTopicView: Boolean) {
        ActivityHelper.launch(
            requireContext(),
            FeedDetailActivity::class.java,
            mapOf("itemId" to item.id, "hideTopicView" to hideTopicView)
        )
    }


    @SuppressLint("SetTextI18n")
    private fun renderAttitude(
        holder: ViewHolder, iconResId: Int, textViewId: Int, containerId: Int,
        index: Int, item: Item, position: Int
    ) {

        holder.setVisibility(containerId, View.GONE)

        item.attitudes?.let { attitudes ->
            if (attitudes.size > index) {

                holder.setImagePath(iconResId, attitudes[index].icon, attitudeImageLoader)

                holder.getView<TextView>(textViewId)?.let {
                    it.text = "" + (item.stat?.getAttitudeCount(index) ?: 0)

                    holder.setTextColor(
                        textViewId,
                        if (item.stat?.isAttitudeGiven(index) == true) R.color.primary_color else R.color.primary_text_color
                    )

                }

                holder.getView<LinearLayout>(containerId)?.let {
                    it.visibility = View.VISIBLE
                    it.setOnClickListener {
                        onAttitudeClick(item, position, index, attitudes[index])

                    }
                }
            }
        }


    }

    private fun onShare(item: Item, position: Int, media: String) {

        presenter.call(
            API.instance()
                .addAction(item.id, Enums.ITEM_TYPE_ITEM, Enums.ACTION_TYPE_SHARED, media),
            {
                item.stat?.incrShareCount()
                this.replace(position, item)
            }
        )
    }

    private fun onAttitudeClick(item: Item, position: Int, index: Int, attitude: Attitude) {
        if (item.stat?.isAttitudeGiven(index) == true) {
            item.attitudes?.let {
                RouterManager.FeedModule.routeToAttitudeUserList(requireContext(), item.id)
//                showAttitudeStatDialog(item, position, index, attitude)
            }
        } else {

            presenter.call(
                API.instance().addAction(
                    item.id,
                    Enums.ITEM_TYPE_ITEM,
                    Enums.ACTION_TYPE_ATTITUDE,
                    attitude.id
                ),
                {
                    item.stat?.incrAttitude(index)
                    this.replace(position, item)
                }
            )
        }
    }

    override fun getItemViewLayoutId(item: Item, position: Int): Int = R.layout.feed_list_item_layout

    private val attitudeImageLoader = object : ViewHolder.ImageLoader {
        override fun loadImage(iv: ImageView, path: String) {
            ImageLoader.loadImage(
                requireContext(), path, iv, requestOptions = RequestOptions().fitCenter()
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
            )
        }
    }


    override fun getItemSkeletonViewLayoutId(): Int {
        return R.layout.feed_list_skeleton_item
    }

}